package com.example.zyghfeedback;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ImageView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class FeedbackList extends AppCompatActivity implements AdapterView.OnItemClickListener {
    private View include;
    private ImageView iv_back, iv_add;
    private RecyclerView recycler_view;
    private MyAdapter mAdapter;
    /**
     * 这个是上拉刷新和加载框架
     */
    private RefreshLayout srl_layout;
    private ClassicsHeader mClassicsHeader;
    //判断是否是第一次进入
    private static boolean isFirstEnter = true;
    //页码
    private int pageNum = 1;
    //每页条数
    private int pageSize = 10;
    //未读消息
    String count;
    //记录刷新时间
    Date delta = null;
    private String ZyKey = "1d3b1b3f67b148b59cdc73e4d2635463";

    private List<MyFeedbackModel> myFeedback = new ArrayList<>();
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            //刷新界面
            mAdapter.notifyDataSetChanged();
//            srl_layout.autoRefresh();
            super.handleMessage(msg);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.feedback_list);
        setInit();
        setOnclick();
    }

    private void setInit() {
        getData();
        srl_layout = findViewById(R.id.srl_layout);
//        int delta = new Random().nextInt(7 * 24 * 60 * 60 * 1000);
        mClassicsHeader = (ClassicsHeader) srl_layout.getRefreshHeader();
        Date nowDate = new Date(System.currentTimeMillis());
        if (isFirstEnter) {
            mClassicsHeader.setLastUpdateTime(nowDate);
            delta = nowDate;
            isFirstEnter = false;
        } else {
            if (delta == null) {
                mClassicsHeader.setLastUpdateTime(nowDate);
                delta = nowDate;
            } else {
                Date daltaDate = new Date(System.currentTimeMillis() - delta.getTime());
                delta = daltaDate;
                mClassicsHeader.setLastUpdateTime(daltaDate);
            }
        }
        mClassicsHeader.setTimeFormat(new SimpleDateFormat("更新于 MM-dd HH:mm", Locale.CHINA));
        mClassicsHeader.setTimeFormat(new DynamicTimeFormat("最后更新： %s"));

        include = findViewById(R.id.include);
        iv_back = include.findViewById(R.id.iv_back);
        iv_add = findViewById(R.id.iv_add);
        recycler_view = (RecyclerView) findViewById(R.id.recycler_view);
        //设置布局管理器
        LinearLayoutManager mLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        recycler_view.setLayoutManager(mLayoutManager);
    }


    private void setOnclick() {
        //设置adapter
        mAdapter = new MyAdapter(myFeedback);
        recycler_view.setAdapter(mAdapter);
        srl_layout.autoRefresh();
        //设置Item添加和移除的动画
        recycler_view.setItemAnimator(new DefaultItemAnimator());
        srl_layout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                myFeedback.clear();
                pageNum = 1;
                getData();
                mAdapter.notifyDataSetChanged();
                refreshlayout.finishRefresh(2000/*,false*/);//传入false表示刷新失败
            }
        });
        srl_layout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                pageNum++;
                getData();
                mAdapter.notifyDataSetChanged();
                refreshlayout.finishLoadMore(2000/*,false*/);//传入false表示加载失败
            }
        });
        iv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        iv_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SharePreferenceUtil mSharePreferenceUtil = SharePreferenceUtil.getInstance(FeedbackList.this);
                mSharePreferenceUtil.seted_fj("");
                mSharePreferenceUtil.seted_idea("");
                Intent intent = new Intent(FeedbackList.this, CommitsActivity.class);
                startActivity(intent);
            }
        });
        mAdapter.setOnItemClickLitener(new MyAdapter.OnItemClickLitener() {
            @Override
            public void onItemClick(View view, int position) {
                MyFeedbackModel myFeedbackModel = myFeedback.get(position);
                Intent intent = new Intent(FeedbackList.this, FeedbackDetails.class);
                intent.putExtra("content", myFeedbackModel.getContent());
                intent.putExtra("source", myFeedbackModel.getSource());
                intent.putExtra("serialNumber", myFeedbackModel.getSerialNumber());
                intent.putExtra("feedbackTime", myFeedbackModel.getFeedbackTime());
                startActivityForResult(intent, 1); // 这里请求码唯一就可以，我这里是 1
//                startActivity(intent);
            }

            @Override
            public void onItemLongClick(View view, int position) {

            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (requestCode == 1) {
            myFeedback.clear();
            //刷新操作
            pageNum = 1;
            getData();
            //设置adapter
//            recycler_view.setAdapter(mAdapter);

        }
    }

    private void getData() {
        //开启线程来发起网络请求
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    MediaType JSON = MediaType.parse("application/json; charset=utf-8");
                    JSONObject json = new JSONObject();
                    try {
                        json.put("zyno", ZyKey);
                        json.put("userId", ZyagUtils.getAndroidID(FeedbackList.this));

//                        json.put("userId", "f6dbfa3560c83115");
                        json.put("pageNum", pageNum);
                        json.put("pageSize", pageSize);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    //1 . 拿到OkHttpClient对象
                    OkHttpClient client = new OkHttpClient();
                    //创建一个RequestBody(参数1：数据类型 参数2传递的json串)
                    RequestBody requestBody = RequestBody.create(JSON, String.valueOf(json));
                    //3 . 构建Request,将FormBody作为Post方法的参数传入
                    Request request = new Request.Builder()
                            .url("http://172.28.60.97:8200/ZYGameServer_v2/app/v2/getMyFeedbackByPage")
                            .post(requestBody)
                            .build();
                    Response response = client.newCall(request).execute();
                    String responseData = response.body().string();
                    getfeedback(responseData);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            //一个JSON对象——JSONObject{}
            //一个JSON数组——JSONArray[]
            private void getfeedback(String responseData) {
                try {
                    JSONObject jsonObject1 = new JSONObject(responseData);
                    JSONArray jsonArray = jsonObject1.getJSONArray("data");
                    for (int i = 0; i < jsonArray.length(); i++) {
                        JSONObject jsonObject = jsonArray.getJSONObject(i);
                        //反馈序列号
                        String serialNumber1 = jsonObject.getString("serialNumber");
                        //回复时间
                        String createTime1 = jsonObject.getString("createTime");
//                        long createTime1 = jsonObject.getLong("createTime");
                        //当前返回状态(0:未解决；1:已解决；2:已搁置)
                        int state1 = jsonObject.getInt("state");
                        //最新回复内容
                        String message1 = jsonObject.getString("message");
                        //反馈内容
                        String content1 = jsonObject.getString("content");
                        //0:未读；1:已读
                        String read1 = jsonObject.getString("read");
                        //消息类型(0:文本；1:图片；；2：系统)
                        String type1 = jsonObject.getString("type");
                        //消息来源(0:用户；1:平台)
                        String source1 = jsonObject.getString("source");
                        //反馈创建时间
                        long feedbackTime1 = jsonObject.getLong("feedbackTime");

                        myFeedback.add(new MyFeedbackModel(serialNumber1, createTime1, state1, message1, content1, read1, type1, source1, feedbackTime1));
                    }
                    Message send_message = Message.obtain();
                    send_message.what = 100;
                    handler.sendMessage(send_message);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private String getUnreadMessage() {
        //开启线程来发起网络请求
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    MediaType JSON = MediaType.parse("application/json; charset=utf-8");
                    JSONObject json = new JSONObject();
                    try {
                        json.put("zyno", "1d3b1b3f67b148b59cdc73e4d2635463");
                        json.put("userId", ZyagUtils.getAndroidID(FeedbackList.this));
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    //1 . 拿到OkHttpClient对象
                    OkHttpClient client = new OkHttpClient();
                    //创建一个RequestBody(参数1：数据类型 参数2传递的json串)
                    RequestBody requestBody = RequestBody.create(JSON, String.valueOf(json));
                    //3 . 构建Request,将FormBody作为Post方法的参数传入
                    Request request = new Request.Builder()
                            .url("http://172.28.60.97:8200/ZYGameServer_v2/app/v2/getUnreadMessageCount")
                            .post(requestBody)
                            .build();
                    Response response = client.newCall(request).execute();
                    String responseData = response.body().string();
                    getfeedback(responseData);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            //一个JSON对象——JSONObject{}
            //一个JSON数组——JSONArray[]
            private void getfeedback(String responseData) {
                try {
                    JSONObject jsonObject1 = new JSONObject(responseData);
                    //未读消息
                    count = jsonObject1.getString("count");
                    Message send_message = Message.obtain();
                    send_message.what = 100;
                    handler.sendMessage(send_message);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }).start();
        return count;
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

    }
}